<template>
  <div class="common-container">
    <!-- 操作区域 -->
    <el-card class="operation-card">
      <div class="operation-buttons">
        <el-button type="primary" @click="openForm(null)">
          <el-icon><Plus /></el-icon> 新增知识库
        </el-button>
        <el-input
          v-model="query.search"
          placeholder="输入关键字搜索知识库名称"
          style="width: 250px; margin-left: 15px"
          clearable
          @keyup.enter="fetchData"
          @clear="fetchData"
        >
          <template #suffix>
            <el-icon class="el-input__icon" @click="fetchData">
              <Search />
            </el-icon>
          </template>
        </el-input>
        <el-select
          v-model="query.category"
          placeholder="分类"
          clearable
          style="width: 150px; margin-left: 15px;"
          @change="fetchData"
        >
          <el-option label="全部" value="" />
          <el-option label="通用" value="general" />
          <el-option label="业务" value="business" />
          <el-option label="技术" value="technical" />
          <el-option label="政策" value="policy" />
        </el-select>
        <el-select
          v-model="query.status"
          placeholder="状态"
          clearable
          style="width: 120px; margin-left: 15px;"
          @change="fetchData"
        >
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </div>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">

            <el-table :data="list" style="width: 100%" border stripe v-loading="loading">
        <el-table-column prop="id" type="index" width="80" />
        <el-table-column prop="name" label="知识库名称" min-width="160" />
        <el-table-column prop="category" label="分类" width="100">
          <template #default="{ row }">
            <el-tag :type="getCategoryTagType(row.category)">
              {{ getCategoryLabel(row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="配置信息" min-width="240">
          <template #default="{ row }">
            <div class="config-info">
              <div>
                <span class="info-label">访问级别：</span>
                <el-tag :type="row.access_level === 'public' ? 'success' : 'warning'" size="small">
                  {{ row.access_level === 'public' ? '公开' : '角色控制' }}
                </el-tag>
              </div>
              <div v-if="row.access_level === 'role_based' && row.allowed_roles && row.allowed_roles.length">
                <span class="info-label">允许角色：</span>
                <el-tag v-for="roleId in row.allowed_roles.slice(0, 2)"
                        :key="roleId"
                        size="small"
                        style="margin-right: 4px;">
                  {{ getRoleName(roleId) }}
                </el-tag>
                <span v-if="row.allowed_roles.length > 2">...</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column prop="updated_at" label="更新时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-container">
              <el-tooltip content="编辑" placement="top">
                <el-button
                  class="action-button"
                  type="primary"
                  circle
                  size="small"
                  @click="openForm(row)"
                >
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button
                  class="action-button"
                  type="danger"
                  circle
                  size="small"
                  @click="handleDelete(row)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 50]"
          @current-change="fetchData"
          @size-change="fetchData"
        />
      </div>
    </el-card>

    <!-- 表单对话框 -->
    <el-dialog v-model="form.visible" title="知识库" width="520px"     :modal="true"
    :append-to-body="true"
    :lock-scroll="true" destroy-on-close>
      <el-form :model="form.model" label-width="100px">
        <el-form-item label="名称" required>
          <el-input v-model="form.model.name" />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="form.model.category" style="width: 100%">
            <el-option label="通用" value="general" />
            <el-option label="业务" value="business" />
            <el-option label="技术" value="technical" />
            <el-option label="政策" value="policy" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.model.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="权重" style="display: none;">
          <el-input-number
            v-model="form.model.search_weight"
            :min="0.1"
            :max="2"
            :step="0.1"
          />
        </el-form-item>
        <el-form-item label="访问级别">
          <el-radio-group v-model="form.model.access_level">
            <el-radio label="public">公开</el-radio>
            <el-radio label="role_based">角色控制</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="form.model.access_level === 'role_based'"
          label="允许角色"
          required
        >
          <el-select
            v-model="form.model.allowed_roles"
            multiple
            placeholder="请选择角色"
            style="width: 100%"
          >
            <el-option
              v-for="role in roleList"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" v-model="form.model.description" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="form.visible=false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Edit, Delete } from '@element-plus/icons-vue'
import {
  getKnowledgeBases, createKnowledgeBase, updateKnowledgeBase, deleteKnowledgeBase
} from '@/api/knowledge'
import { getRoleList } from '@/api/role'

defineOptions({
  name: 'KnowledgeBasesPage'
})

const loading = ref(false)
const list = ref([])
const roleList = ref([])
const query = reactive({ search: '', category: '', status: '' })
const pagination = reactive({ current: 1, size: 10, total: 0 })
const form = reactive({
  visible: false,
  model: {
    id: null,
    name: '',
    category: 'general',
    status: 1,
    search_weight: 1.0,
    access_level: 'public',
    allowed_roles: [],
    description: ''
  }
})

// 根据角色ID获取角色名称
const getRoleName = computed(() => {
  return (roleId) => {
    const role = roleList.value.find(r => r.id == roleId)
    return role ? role.name : `角色${roleId}`
  }
})

// 获取分类标签类型
const getCategoryTagType = (category) => {
  const types = {
    'general': 'info',
    'business': 'success',
    'technical': 'primary',
    'policy': 'warning'
  }
  return types[category] || 'info'
}

// 获取分类标签文本
const getCategoryLabel = (category) => {
  const labels = {
    'general': '通用',
    'business': '业务',
    'technical': '技术',
    'policy': '政策'
  }
  return labels[category] || category
}

// 获取知识库列表
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      skip: (pagination.current - 1) * pagination.size,
      limit: pagination.size,
      search: query.search || undefined,
      category: query.category || undefined,
      status_filter: query.status === '' ? undefined : query.status,
    }
    const res = await getKnowledgeBases(params)
    list.value = res.data || []
    pagination.total = res.total || 0
  } catch (e) {
    console.error(e)
    ElMessage.error('获取知识库失败')
  } finally {
    loading.value = false
  }
}

// 获取角色列表
const fetchRoles = async () => {
  try {
    const res = await getRoleList({ page: 1, size: 100 })
    roleList.value = res.items || []
  } catch (e) {
    console.error(e)
    ElMessage.error('获取角色列表失败')
  }
}

// 打开表单
const openForm = (row) => {
  if (row) {
    form.model = {
      ...row,
      allowed_roles: Array.isArray(row.allowed_roles) ? row.allowed_roles : []
    }
  } else {
    form.model = {
      id: null,
      name: '',
      category: 'general',
      status: 1,
      search_weight: 1.0,
      access_level: 'public',
      allowed_roles: [],
      description: ''
    }
  }
  form.visible = true
}

// 提交表单
const submitForm = async () => {
  // 表单验证
  if (!form.model.name.trim()) {
    ElMessage.error('请输入知识库名称')
    return
  }
  if (form.model.access_level === 'role_based' && (!form.model.allowed_roles || form.model.allowed_roles.length === 0)) {
    ElMessage.error('角色控制模式下必须选择至少一个角色')
    return
  }

  const data = new URLSearchParams()
  data.set('name', form.model.name)
  data.set('description', form.model.description || '')
  data.set('category', form.model.category || 'general')
  data.set('status_value', form.model.status)
  data.set('search_weight', form.model.search_weight)
  data.set('access_level', form.model.access_level || 'public')

  // 只有角色控制时才传递角色信息
  if (form.model.access_level === 'role_based' && form.model.allowed_roles && form.model.allowed_roles.length > 0) {
    data.set('allowed_roles', JSON.stringify(form.model.allowed_roles))
  }

  try {
    if (form.model.id) {
      await updateKnowledgeBase(form.model.id, data)
    } else {
      await createKnowledgeBase(data)
    }
    ElMessage.success('保存成功')
    form.visible = false
    fetchData()
  } catch (err) {
    console.error(err)
    ElMessage.error('保存失败')
  }
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确认删除知识库「${row.name}」吗？`, '提示', { type: 'warning' })
    await deleteKnowledgeBase(row.id)
    ElMessage.success('删除成功')
    fetchData()
  } catch (e) {
    console.error(e)
  }
}

onMounted(async () => {
  await fetchRoles()
  await fetchData()
})
</script>

<style scoped>
.common-container {
  padding: 20px;
  height: calc(100vh - 180px);
  display: flex;
  flex-direction: column;
}

.operation-card {
  margin-bottom: 20px;
}

.operation-buttons {
  display: flex;
  align-items: center;
}

.table-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

:deep(.el-card__body) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.el-table) {
  flex: 1;
  overflow: auto;
}

.config-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.info-label {
  font-weight: bold;
  margin-right: 5px;
  color: #606266;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.action-container {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
}

.action-button {
  font-size: 12px;
  border: none;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.action-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
</style>
